import { createRouter, createWebHistory } from 'vue-router'

import { message } from 'ant-design-vue';
import { getUserToken } from '@/utils/cache';
import IndexPage from '../views/Home/Home.vue';

export const routes = [
  // 解决页面无重定向问题
  // {
  //   path: '/',
  //   name: 'Home',
  //   component: IndexPage,
  // },
  {
    path: '/',
    redirect: () => {
      window.location.href = '/home/index.html'
    },
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    children: [
      // {
      //   path: '',
      //   redirect: '/index'
      // },
      {
        path: 'index',
        children: [
          {
            path: '/home/index.html',
            name: 'Home',
            component: () => import('../views/Home/Home.vue'),
            meta: { requiresAuth: false }
          }
        ]
      },
      // 修改详情页
      {
        path: 'details',
        name: 'GoodDetails',
        component: () => import('../views/GoodDetails/GoodDetails.vue'),
        meta: {
          prerender: true
        }
      },
      {
        path: 'login',
        name: 'Login',
        component: () => import('../views/Login.vue'),
      },
      {
        path: 'register',
        name: 'Register',
        component: () => import('../views/Register.vue'),
      },
      {
        path: 'product/:url',
        name: 'ProductDetail',
        component: () => import('../views/GoodDetails/GoodDetails.vue'),
        meta: {
          prerender: true
        }
      },
      // {
      //   path: '/products',
      //   name: 'Products',
      //   component: () => import('../views/ProductList/ProductList.vue'),
      //   meta: { requiresAuth: false }
      // },
      {
        path: '/classify/:url',
        name: 'Products',
        component: () => import('../views/ProductList/ProductList.vue'),
        meta: { requiresAuth: false }
      },
      {
        name: 'cancelAccount',
        path: '/cancelAccount',
        component: () => import("../views/CancelAccount.vue")
      },
      // 隐私协议
      // {
      //   path: '/privacy-policy',
      //   name: 'Privacy-policy',
      //   component: () => import('../views/PrivacyPolicy.vue'),
      //   meta: { requiresAuth: false }
      // },

      {
        path: '/blog-post',
        name: 'BlogPost',
        component: () => import('../views/BlogPost/blog-post.vue'),
        meta: { requiresAuth: false }
      },
      {
        path: '/empower-her-journey-with-goladies',
        name: 'EmpowerHerJourneyWithGoladies',
        component: () => import('../views/BlogPost/EmpowerHer.vue'),
        meta: { requiresAuth: false }
      },
      {
        path: '/blog-left-menu',
        name: 'BlogLeftMenu',
        component: () => import('../views/BlogPost/BlogLeftMenu.vue'),
        meta: { requiresAuth: false }
      },
      {
        path: '/company-info-menu',
        name: 'CompanyInfoMenu',
        component: () => import('../views/BlogPost/CompanyInfoMenu.vue'),
        meta: { requiresAuth: false }
      },
      {
        path: 'user',    //用户中心的 所有路由 都在这里都在这里  
        // component: () => import('@/layouts/MainLayout.vue'),
        redirect: '/user/profile',
        meta: { requiresAuth: true },
        children: [
          {
            path: 'profile',
            name: 'UserProfile',
            component: () => import('@/views/user/ProfileView.vue'),
            meta: { title: '个人资料', requiresAuth: true }
          },
          {
            path: 'orders',
            name: 'UserOrders',
            component: () => import('@/views/user/OrdersView.vue'),
            meta: { title: '我的订单', requiresAuth: true }
          },
          {
            path: 'settings',
            name: 'UserSettings',
            component: () => import('@/views/user/SettingsView.vue'),
            meta: { title: '账户设置', requiresAuth: true }
          },
          {
            path: 'wishlist',
            name: 'UserWishlist',
            component: () => import('@/views/user/WishlistView.vue'),
            meta: { title: '我的收藏', requiresAuth: true }
          },
          {
            path: 'address',
            name: 'UserAddress',
            component: () => import('@/views/user/AddressesView.vue'),
            meta: { title: '我的地址', requiresAuth: true }
          },
          {
            path: 'history',
            name: 'UserHistory',
            component: () => import('@/views/user/HistoryView.vue'),
            meta: { title: '我的浏览', requiresAuth: true }
          },
          {
            path: 'cart',
            name: 'UserCart',
            component: () => import('@/views/user/CartView.vue'),
            meta: { title: '我的购物车', requiresAuth: true }
          },
          {
            path: 'checkout',
            name: 'Checkout',
            component: () => import('@/views/user/CheckoutView.vue'),
            meta: { title: '结算', requiresAuth: true }
          },
          {
            path: 'points',
            name: 'UserPoints',
            component: () => import('@/views/user/PointsView.vue'),
            meta: { title: '我的积分', requiresAuth: true }
          },
          {
            path: 'coupons',
            name: 'UserCoupons',
            component: () => import('@/views/user/CouponsView.vue'),
            meta: { title: '我的优惠券', requiresAuth: true }
          },
          {
            path: 'message',
            name: 'UserMessage',
            component: () => import('@/views/user/NotificationsView.vue'),
            meta: { title: '我的消息通知', requiresAuth: true }
          }

        ]
      },
      {
        path: '/help',
        component: () => import('../views/Help/index.vue'), // 当前这个组件
        children: [
          {
            path: 'returns/how-to-return',
            component: () => import('../views/Help/Return/returns.vue')
          },
          {
            path: 'returns/refunds-information',
            component: () => import('../views/Help/Return/refunds.vue')
          },
          {
            path: 'returns/key-returns-information',
            component: () => import('../views/Help/Return/KeyReturnsInformation.vue')
          },
          {
            path: 'account/signing-in-to-my-account',
            component: () => import('../views/Help/MyAccount/SigningInToMyAccount.vue')
          },
          {
            path: 'account/i-have-forgotten-my-password',
            component: () => import('../views/Help/MyAccount/IHaveForgottenMyPassword.vue')
          },
          {
            path: 'account/opening-an-account',
            component: () => import('../views/Help/MyAccount/OpeningAnAccount.vue')
          },
          {
            path: 'delivery/i-have-a-problem-with-my-delivery',
            component: () => import('../views/Help/Delivery/IHaveAProblemWithMyDelivery.vue')
          },
          {
            path: 'delivery/delivery-key-information',
            component: () => import('../views/Help/Delivery/DeliveryKeyInformation.vue')
          },
          {
            path: 'delivery/tracking-my-order',
            component: () => import('../views/Help/Delivery/TrackingMyOrder.vue')
          },
          {
            path: 'payments/help-with-payments',
            component: () => import('../views/Help/Payments/HelpWithPayments.vue')
          },
          {
            path: 'payments/what-payment-methods-can-i-use',
            component: () => import('../views/Help/Payments/WhatPaymentMethodsCanIUse.vue')
          },
          {
            path: 'shopping/has-my-order-gone-through',
            component: () => import('../views/Help/Shopping/HasMyOrderGoneThrough.vue')
          },
          {
            path: 'shopping/amend-cancel-my-order',
            component: () => import('../views/Help/Shopping/AmendCancelMyOrder.vue')
          }
          ,
          {
            path: 'shopping/placing-an-order',
            component: () => import('../views/Help/Shopping/PlacingAnOrder.vue')
          },

          {
            path: 'other/i-have-a-complaint',
            component: () => import('../views/Help/Other/IHaveAComplaint.vue')
          },
          {
            path: 'other/sizing-guides',
            component: () => import('../views/Help/Other/SizingGuides.vue')
          },
          {
            path: 'other/contact-us',
            component: () => import('../views/Help/Other/ContactUs.vue')
          }
        ]
      },
      {
        path: '/privacypolicy',
        name: 'PrivacyPolicy',
        component: () => import('../views/Help/privacypolicy.vue'),
      },
      {
        path: '/FAQs',
        name: 'FAQs',
        component: () => import('../views/Help/FAQs.vue'),
      },
      {
        path: '/termsService',
        name: 'TermsService',
        component: () => import('../views/Help/TermsService.vue'),
      },
      {
        path: '/story',
        name: 'Story',
        component: () => import('../views/Help/story.vue'),
      },
      // 可持续性页面
      {
        path: '/sustainability',
        name: 'Sustainability',
        component: () => import('../views/Help/Sustainability.vue'),
      },
      {
        path: '/searchProduct',
        name: 'SearchProduct',
        component: () => import('../views/SearchProduct/index.vue'),
      },
    ]
  },

  {
    path: '/forgetPassword',
    name: 'ForgetPassword',
    component: () => import('../views/ForgetPassword/index.vue'),
    meta: { requiresAuth: false }
  },
]

const router = createRouter({
  scrollBehavior: () => ({ left: 0, top: 0 }),
  history: createWebHistory(),
  routes,
})

// 需要跳转到登录页的路径
const redirectToLoginPaths = ['/user'];

// 需要提示未登录但不跳转的路径
const showAlertPaths = ['/cart/checkout', '/product/buy'];

router.beforeEach((to, from, next) => {
  // 检查是否需要登录权限
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  // 使用新的getUserToken函数检查token
  const hasToken = !!getUserToken();

  // 如果路由需要认证且没有token
  if (requiresAuth && !hasToken) {
    // 检查是否是需要直接跳转到登录页的路径
    const shouldRedirect = redirectToLoginPaths.some(path => to.path.startsWith(path)) ||
      to.path.startsWith('/user');

    // 检查是否是需要提示但不跳转的路径
    const shouldShowAlert = showAlertPaths.some(path => to.path.startsWith(path));

    if (shouldRedirect) {
      // 重定向到登录页
      next('/login');
    } else if (shouldShowAlert) {
      message.warning('请先登录后再操作');
      // 停留在当前页面
      next(false);
    } else {
      // 其他需要认证的路径，默认跳转到登录页
      next('/login');
    }
  } else {
    // 不需要认证或已有token，正常导航
    next();
  }
})

export default router
